package com.gem.back.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.gem.back.entity.AoaUserLoginRecord;
import com.gem.back.service.IAoaUserLoginRecordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author hhhy
 * @since 2020-02-22
 */
@Controller
@RequestMapping("/record")
public class AoaUserLoginRecordController {
    @Autowired
    private IAoaUserLoginRecordService aoaUserLoginRecordService;

    @RequestMapping("/logrecord")
    public String userRecord(Model model) {
        List<AoaUserLoginRecord> loginRecord = aoaUserLoginRecordService.list();
        model.addAttribute("userrecord",loginRecord);
        return "user/userlogrecordmanagetable";
    }

    //显示本周的每天的记录
    @RequestMapping("countweeklogin")
    @ResponseBody
    public Integer[] dfsa(HttpServletResponse response) throws IOException {
        Integer[]r=new Integer[7];
        Calendar calendar= Calendar.getInstance();
        setToFirstDay(calendar);
        for (int i = 0; i < 7; i++) {
            SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
            QueryWrapper<AoaUserLoginRecord> queryWrapper = new QueryWrapper<>();
            queryWrapper.like("login_time",sdf.format(calendar.getTime()));
            r[i]=aoaUserLoginRecordService.count(queryWrapper);
            calendar.add(Calendar.DATE, 1);
        }
        return r;
    }

    private static void setToFirstDay(Calendar calendar) {
        while (calendar.get(Calendar.DAY_OF_WEEK) != Calendar.MONDAY) {
            calendar.add(Calendar.DATE, -1);
        }
    }
    //给hashMap按照value排序
    public static ArrayList<Map.Entry<String, Integer>> sortMap(Map map){
        List<Map.Entry<String, Integer>> entries = new ArrayList<Map.Entry<String, Integer>>(map.entrySet());
        Collections.sort(entries, new Comparator<Map.Entry<String, Integer>>() {
            public int compare(Map.Entry<String, Integer> obj1 , Map.Entry<String, Integer> obj2) {
                return obj2.getValue() - obj1.getValue();
            }
        });
        return (ArrayList<Map.Entry<String, Integer>>) entries;
    }
}
